package com.ushio.capsuleservice.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ushio.capsuleservice.model.dto.ApiResponse;
import com.ushio.capsuleservice.model.entity.Post;
import com.ushio.capsuleservice.service.PostService;
import com.ushio.capsuleservice.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;

/**
 * 帖子控制器
 */
@RestController
@RequestMapping("/api/post")
@CrossOrigin(origins = "*")
public class PostController {
    
    @Autowired
    private PostService postService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 创建帖子
     */
    @PostMapping
    public ApiResponse<Post> createPost(@RequestBody Post post, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            Long userId = jwtUtil.getUserIdFromToken(token);
            post.setUserId(userId);
            
            Post createdPost = postService.createPost(post);
            return ApiResponse.success("创建成功", createdPost);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取帖子列表
     */
    @GetMapping
    public ApiResponse<IPage<Post>> getPostList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword) {
        try {
            IPage<Post> postList = postService.getPostList(page, size, keyword);
            return ApiResponse.success(postList);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 获取帖子详情
     */
    @GetMapping("/{id}")
    public ApiResponse<Post> getPostDetail(@PathVariable Long id) {
        try {
            Post post = postService.getPostDetail(id);
            if (post == null) {
                return ApiResponse.error("帖子不存在");
            }
            return ApiResponse.success(post);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 更新帖子
     */
    @PutMapping("/{id}")
    public ApiResponse<Post> updatePost(@PathVariable Long id, @RequestBody Post post, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 检查是否是帖子作者
            Post existingPost = postService.getById(id);
            if (existingPost == null || !existingPost.getUserId().equals(userId)) {
                return ApiResponse.error("无权限修改此帖子");
            }
            
            Post updatedPost = postService.updatePost(id, post);
            return ApiResponse.success("更新成功", updatedPost);
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 删除帖子
     */
    @DeleteMapping("/{id}")
    public ApiResponse<String> deletePost(@PathVariable Long id, HttpServletRequest request) {
        try {
            String token = getTokenFromRequest(request);
            Long userId = jwtUtil.getUserIdFromToken(token);
            
            // 检查是否是帖子作者
            Post existingPost = postService.getById(id);
            if (existingPost == null || !existingPost.getUserId().equals(userId)) {
                return ApiResponse.error("无权限删除此帖子");
            }
            
            boolean success = postService.deletePost(id);
            if (success) {
                return ApiResponse.success("删除成功", null);
            } else {
                return ApiResponse.error("删除失败");
            }
        } catch (Exception e) {
            return ApiResponse.error(e.getMessage());
        }
    }
    
    /**
     * 从请求中获取token
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        throw new RuntimeException("未找到有效的token");
    }
}
